package com.itjeffrey.autocode.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @From: Jeffrey
 * @Date: 2021/6/5
 */
@Configuration //配置类
@EnableAsync //启用异步线程池
public class ThreadPoolConfig {

    @Value("${async.thread.pool.executor.coreCount}")
    private int corePoolCount;

    @Value("${async.thread.pool.executor.maxCount}")
    private int maxPoolCount;

    @Value("${async.thread.pool.executor.queueSize}")
    private int queueSize;

    @Value("${async.thread.pool.executor.namePrefix}")
    private String threadNamePrefix;

    /**
     * 在需要用到异步线程处理的方法上添加 @Async("asyncThreadPoolExecutor")即可执行异步线程处理
     *
     * @return
     */
    @Bean
    public Executor asyncThreadPoolExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new LoggerThreadPoolTaskExecutor();
        //配置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(corePoolCount);
        //配置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolCount);
        //配置阻塞队列深度
        threadPoolTaskExecutor.setQueueCapacity(queueSize);
        //配置线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        //配置拒绝执行处理器 当线程池已经达到最大线程数maxPoolCount时，处理新任务的策略
        //CallerRunsPolicy 不在新线程中执行任务，而是由调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
